﻿using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Windows;
using System.Windows.Browser;

namespace Helper
{
    public abstract class ServiceBase : IApplicationService, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        [ScriptableMember]
        public event EventHandler<ScriptablePropertyChangedEventArgs> ScriptablePropertyChanged;
       

        protected void RaisePropertyChanged(string propertyName, object value)
        {
            if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            if (this.ScriptablePropertyChanged != null)
            {
                try { this.ScriptablePropertyChanged(this, new ScriptablePropertyChangedEventArgs(propertyName, value)); }
                catch (Exception ex) { this.ReportErrorToDOM(ex); }
            }
        }

        protected void ReportErrorToDOM(Exception e)
        {
            try
            {
                string str = (e.Message + e.StackTrace).Replace('"', '\'').Replace("\r\n", @"\n");
                HtmlPage.Window.Eval("throw new Error(\"" + str + "\");");
            }
            catch (Exception){ }
        }

        protected bool SetPropertyValue<T>(ref T field, T value, Expression<Func<object>> expression)
        {
            return this.SetPropertyValue<T>(ref field, value, expression, null);
        }

        protected bool SetPropertyValue<T>(ref T field, T value, Expression<Func<object>> expression, Action onchange)
        {
            bool flag = object.Equals((T) field, value);
            if (!flag)
            {
                field = value;
                if (onchange != null)
                {
                    onchange();
                }
                MemberExpression body = expression.Body as MemberExpression;
                if (body == null)
                {
                    UnaryExpression expression3 = expression.Body as UnaryExpression;
                    if (expression3 != null)
                    {
                        body = expression3.Operand as MemberExpression;
                    }
                }
                string name = body.Member.Name;
                this.RaisePropertyChanged(name, value);
            }
            return flag;
        }

        protected abstract void StartService(ApplicationServiceContext context);
        protected abstract void StopService();
        void IApplicationService.StartService(ApplicationServiceContext context)
        {
            this.StartService(context);
        }

        void IApplicationService.StopService()
        {
            this.StopService();
        }
    }
}

